<?php

class UsersController extends AppController {

	public function index() {
		
		//This will setup default query conditions
		$conditions = array(
				'contain' => false,
    			'order' => array('lastname ASC', 'firstname ASC')
    	);

		//This will get current user 
		$curruser = $this->Session->read('User');

		//If not a superuser, listing will only be for his organization
		if ( $curruser['User']['access_level'] > 0 ) {
			//$conditions['conditions'] = array('Organization.id' => $curruser['User']['organization_id']);
			$conditions['conditions']['Organization.id'] = $curruser['User']['organization_id'];
		}

		//If not an admin, listing will only be for his deparment and division		
		//if ( $curruser['User']['access_level'] > 1 ) {
		//	$conditions['conditions']['Department.id'] = $curruser['User']['department_id'];
		//	$conditions['conditions']['Division.id'] = $curruser['User']['division_id'];
		//}
		
		//$conditions['conditions']['Ledger.status'] = 'A';


		$users = $this->User->find('all', 
			$conditions);
		
		
		//$users = $this->User->find('all');
		$this->set('users', $users);
		
	}
	
	public function login() {
	
		if ( $this->Session->check('User') ) {	
				$this->redirect(array(
					'controller' => 'home',
					'action' => 'index'
				));
		}
	
		//$this->layout = 'guest';
		$this->layout = 'login';
	
		if ( $this->request->is('post') ){
		
			// Find method
			/*
			$user = $this->User->find('first', array(
				'conditions' => array(
					'username' => $this->request->data('User.username'),
					'password' => $this->request->data('User.password')
					)
				));
			
			debug($user);
			
			*/	
			
			// Magical
			
			$user = $this->User->findByEmailAndPassword($this->request->data('User.email'),$this->request->data('User.password'));
			
			if( $user ) {
			
				$this->Session->write('User', $user);
				$this->redirect(array(
					'controller' => 'home',
					'action' => 'index'
				));
			
			}
			
			$this->Session->setFlash('Email and password combindation are not correct.');
			
		}
	
	}
	
	public function logout() {

		$this->Session->destroy('User');
				$this->redirect(array(
					'controller' => 'users',
					'action' => 'login'
				));				
	}
	
}

?>